#!/usr/bin/env node

// Code from cavy-cli https://github.com/pixielabs/cavy-cli
const express = require("express");
const server = express();
const chalk = require("chalk");
const program = require("commander");
const cors = require("cors");

server.use(cors({origin: "*", credentials: true}));
server.use(express.json());

function countString(count, str) {
    let string = count == 1 ? str : str + "s";
    return `${count} ${string}`;
}

server.post("/report", (req, res) => {
    const results = req.body["results"];
    const errorCount = req.body["errorCount"];
    const duration = req.body["duration"];

    results.forEach((result, index) => {
        message = `${index + 1}) ${result["message"]}`;

        if (result["passed"]) {
            console.log(chalk.green(message));
        } else {
            console.log(chalk.red(message));
        }
    });

    console.log(`Finished in ${duration} seconds`);
    const endMsg = `${countString(results.length, "test")}, ${countString(
        errorCount,
        "failure"
    )}`;

    if (!errorCount) {
        console.log(chalk.green(endMsg));
        res.send("ok");
        process.exit(0);
    } else {
        console.log(chalk.red(endMsg));
        res.send("failed");
        process.exit(1);
    }
});

server.get("/", (req, res) => {
    res.send("cavy-cli running");
});

program
    .option(
        "-p, --port <NUMBER>",
        "custom port number (default 8082)",
        parseInt
    )
    .parse(process.argv);

if (program.port === undefined) {
    program.port = 8082;
} else if (isNaN(program.port) || program.port <= 0) {
    console.error("error: port argument must be a positive number");
    program.outputHelp();
    process.exit(1);
}

server.listen(program.port, () =>
    console.log(
        `Cavy report server: listenning on port ${
            program.port
        } for tests results...`
    )
);
